package gui;

import gui.events.CreateDatabaseEvent;
import gui.interfaces.ICreateDatabaseEventListener;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class PanelCreateDatabase extends JPanel {
	private List _listeners = new ArrayList();
	private JTextField textField;

	public String getDatbaseName() {
		return textField.getText();
	}

	private final JButton btnCreate = new JButton("Create");

	/**
	 * Create the panel.
	 */
	public PanelCreateDatabase() {
		setLayout(new BorderLayout(0, 0));

		JPanel panelImageCreateDatabase = new JPanel();
		add(panelImageCreateDatabase, BorderLayout.WEST);

		JPanel panel = new JPanel();
		add(panel, BorderLayout.CENTER);
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel lblDatabaseName = new JLabel("Database name :");
		panel.add(lblDatabaseName);

		textField = new JTextField();
		panel.add(textField);
		textField.setColumns(20);

		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.SOUTH);
		panel_1.setLayout(new BorderLayout(0, 0));

		JPanel panel_2 = new JPanel();
		panel_1.add(panel_2, BorderLayout.NORTH);
		panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		btnCreate.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				fireApplyEvent();
			}
		});
		panel_2.add(btnCreate);

		JButton btnCancel = new JButton("Cancel");
		btnCancel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				fireCancelEvent();
			}
		});
		panel_2.add(btnCancel);

	}

	@SuppressWarnings("unchecked")
	public synchronized void addCreateDatabaseEventListener(
			ICreateDatabaseEventListener listener) {
		_listeners.add(listener);
	}

	public synchronized void removeCreateDatabaseEventListener(
			ICreateDatabaseEventListener listener) {
		_listeners.remove(listener);
	}

	private synchronized void fireCancelEvent() {
		CreateDatabaseEvent event = new CreateDatabaseEvent(this);
		Iterator i = _listeners.iterator();
		while (i.hasNext()) {
			((ICreateDatabaseEventListener) i.next()).cancel(event);
		}
	}

	private synchronized void fireApplyEvent() {
		CreateDatabaseEvent event = new CreateDatabaseEvent(this);
		Iterator i = _listeners.iterator();
		while (i.hasNext()) {
			((ICreateDatabaseEventListener) i.next()).apply(event);
		}
	}
}
